/**
 * 
 */
package com.p2p.base.interceptors;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import com.p2p.base.annotation.PermissionNeed;
import com.p2p.base.model.BackendUser;
import com.p2p.base.util.LoginUtil;

/**
 * @author ruiqi
 *
 */
public class BackendPermissionInterceptor extends HandlerInterceptorAdapter{

	private final Logger logger = LoggerFactory
			.getLogger(BaseLoginInterceptor.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		Object o = LoginUtil.getCurrentUser();
		if(o==null){
			return false;
		}
		
		if (handler instanceof ResourceHttpRequestHandler) {
			return true;
		}
		
		
		//如果是超级用户
		BackendUser user = (BackendUser)o;
		if(user.getId()==1){
			return true;
		}
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Class<?> type = handlerMethod.getBeanType();
		// Method method = handlerMethod.getMethod();
		// 判断是否需有loginNeedless标记
		PermissionNeed permitionNeed = type.getAnnotation(PermissionNeed.class);
		if (permitionNeed == null) {
			permitionNeed = type.getSuperclass().getAnnotation(PermissionNeed.class);
		}
		
		if (permitionNeed == null) {
			permitionNeed = handlerMethod
					.getMethodAnnotation(PermissionNeed.class);
		}
		if(permitionNeed==null){
			return true;
		}
		boolean permit = checkPermit(permitionNeed);
		if(permit){
			return true;
		}else{
			doPermitionNeed(response);
			return false;
		}
		
		
	}
	
	protected void doPermitionNeed(HttpServletResponse response){
				response.setContentType("application/json");
				PrintWriter pWriter = null;
				try {
					pWriter = response.getWriter();
					pWriter.write("no permition");
				} catch (IOException e) {
					logger.error("", e);
				} finally {
					if (pWriter != null) {
						pWriter.flush();
						pWriter.close();
					}
				}
	}
	
	private boolean checkPermit(PermissionNeed permitionNeed ){
		String permitValues = permitionNeed.value();
		if(StringUtils.isBlank(permitValues)){
			return true;
		}
		//Integer permitInteger = Integer.valueOf(permitValues);
		BackendUser user = (BackendUser)LoginUtil.getCurrentUser();
		List<String> permitList = user.getPermitList();
		
		if(permitList.contains(permitValues)){
			return true;
		}else{
			return false;
		}
	}
}
